#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#define MAX 256
char *buffer;
// sem_t empty; //定义同步信号量 empty
// sem_t full;  //定义同步信号量 full
// sem_t mutex; //定义互斥信号量 mutex
sem_t rmutex;      //读者信号量
sem_t wmutex;      //写者信号量
int readCount = 0; //正在读的进程数
void *writer()
{
    // while (1)
    // {
        sem_wait(&wmutex);
        printf("input something to buffer:");
        fgets(buffer, MAX, stdin);
        sem_post(&wmutex);
    // }
}
void *reader()
{
    // while (1)
    // {
        sem_wait(&rmutex);
        if (readCount == 0)
            sem_wait(&wmutex);
        readCount++;
        sem_post(&rmutex);

        printf("read product from buffer:%s", buffer);
        memset(buffer, 0, MAX);

        sem_wait(&rmutex);
        readCount--;
        if (readCount == 0)
            sem_post(&wmutex);
        sem_post(&rmutex);
    // }
}
int main()
{
    pthread_t id_writer;
    pthread_t id_reader;
    int ret;
    sem_init(&rmutex, 0, 1); //设置 empty 到初值为 10
    sem_init(&wmutex, 0, 1); //设置 full 到初值为 0
    buffer = (char *)malloc(MAX);

    ret = pthread_create(&id_reader, NULL, reader, NULL);
    ret = pthread_create(&id_writer, NULL, writer, NULL);
    pthread_join(id_writer, NULL); //等待生产者线程结束
    pthread_join(id_reader, NULL); //等待消费者线程结束
    sem_destroy(&wmutex);          //删除信号量
    sem_destroy(&rmutex);
    printf("The End...\n");
}